package cn.tq365.util.baidu;

import java.io.File;
import java.io.FileInputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map.Entry;
import java.util.Properties;

import javax.xml.namespace.QName;
import javax.xml.ws.Service;

import com.baidu.api.client.core.ClientInternalException;
import com.baidu.api.client.core.CoreService;
import com.baidu.api.client.core.VersionService;
import com.baidu.api.client.version.Version;

@SuppressWarnings("restriction")
public class SyncServiceFactory extends VersionService {
	public static final Properties props = new Properties();
	public static final String apiPath = Thread.currentThread()
			.getContextClassLoader().getResource("baidu-api.properties")
			.getPath();
	static {
		// 该类在第一次被调用的时候执行
		try {
			// 读取配置文件
			props.load(new FileInputStream(apiPath));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public SyncServiceFactory(String userName, String passwords) {
		props.setProperty("username", userName);
		props.setProperty("password", passwords);
		readConfig(props);
		this.generateHeader();
	}

	public static SyncServiceFactory getInstance(String userName,
			String password) {
		return new SyncServiceFactory(userName, password);
	}

	/**
	 * 用于修改配置属性
	 * 
	 * @param file
	 * @return
	 */
	public static boolean update(File file) {
		// 实现暂略
		// step1:修改props
		// step2:上传并覆盖原有的配置文件
		return true;
	}

	// /////////////////////////////////////////////////////////////////////////////
	// Protected or private methods
	// /////////////////////////////////////////////////////////////////////////////

	protected <T> T getInternalService(Class<T> cls, Version v) {
		if (cls == null || v == null)
			throw new IllegalArgumentException("Null parameter is not allowed!");
		Service service;
		try {
			String addr = v.getAddr(cls);
			QName qName = v.getQName(cls);
			if (addr == null || qName == null)
				throw new ClientInternalException("Service ["
						+ cls.getSimpleName() + "] not supported by version - "
						+ v.getVersion());
			service = new CoreService(new URL(serverUrl + addr), qName);
			// service.setExecutor(executor);
			return service.getPort(cls);
		} catch (MalformedURLException e) {
			throw new ClientInternalException(e);
		}
	}

	private void readConfig(Properties props) {
		for (Entry<Object, Object> entry : props.entrySet()) {
			String key = entry.getKey().toString();
			String value = entry.getValue().toString();
			super.setConfig(key, value);
			System.out.println(key + ":" + value);
		}
	}

}
